<?php

namespace app\common;

use GuzzleHttp\Client;
use think\facade\Db;

class ExchangeRateHostAPI
{
    private $client;

    public function __construct()
    {
        //        $this->client = new Client([
        //            'base_uri' => 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=50494&group=huilv_minute&tab_id=1&oe=utf-8&need_reverse_real=1&query=' . $fromCurrency . $toCurrency
        //        ]);
    }

    /**
     * 获取汇率
     * @param $fromCurrency
     * @param $toCurrency
     * @return int|null
     * 2024-12-16 14 01 55
     * author: jiang
     */
    public function getRate($fromCurrency, $toCurrency)
    {
        $key = date('Y-m-d') . $fromCurrency . $toCurrency . '_rate';
        $redis = new RedisClient();
        $data = $redis->get($key);

        if (!$data) {
            $data = $this->getRemote($fromCurrency, $toCurrency);
            if (is_numeric($data)) {
                $redis->set($key, $data);
                $redis->setExpiry($key, 172800);
            }
        }
        return $data;
    }
    /**
     * @describe 根据币种获取汇率
     * @author: Bobo
     * @date: 2025-08-04 10:57:10 
     * @param int $fromCurrency
     * @param int $toCurrency
     * @return Renderable
     */
    public function getRateByCurrencyId(int $fromCurrency, int $toCurrency)
    {

        $currency = Db::name('transaction_currency')->whereIn('id', [$fromCurrency, $toCurrency])->select()->toArray();
        if (empty($currency) || count($currency) != 2) {
            return 0;
        }
        $currency = array_column($currency, null, 'id');
        return $this->getRate($currency[$fromCurrency]['abbr'], $currency[$toCurrency]['abbr']);
    }

    /**
     * 远程获取汇率
     * @param $fromCurrency
     * @param $toCurrency
     * @return int|null
     * 2024-12-16 14 02 03
     * author: jiang
     */
    public function getRemote($fromCurrency, $toCurrency)
    {
        try {
            // 设置API endpoint URL
            $url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=50494&group=huilv_minute&tab_id=1&oe=utf-8&need_reverse_real=1&query=" . $fromCurrency . $toCurrency;
            $currentrate = 0;
            $result = $this->curl_get($url);
            if ($result && isset(json_decode($result)->data[0]->cur->num)) {
                $currentrate = json_decode($result)->data[0]->cur->num;
            }

            return $currentrate;
        } catch (\Exception $e) {
            return 'Exception: ' . $e->getMessage();;
        }
    }

    function curl_get($url, &$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2); // 总的请求超时时间
        $file_contents = curl_exec($ch);
        // 检查是否有错误发生
        if (curl_errno($ch)) {
            throw new \Exception('Curl error: ' . curl_error($ch));
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }
}
